import {
	login,
	smsLogin,
	emailLogin,
	logout,
	getInfo,
} from '@/api/login'
import {
	getToken,
	setToken,
	removeToken,
	getUserInfo,
	setUserInfo,
	removeUserInfo
} from '@/libs/auth'

const user = {
	state: () => ({
		token: null,
		userInfo: null, // 用户信息
	}),

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_USER: (state, userInfo) => {
			state.userInfo = userInfo;
		},
	},

	actions: {
		// 登录
		Login({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				login(this.$axios, data).then(res => {
					if (res.code == 200) {
						setToken(res.data)
						commit('SET_TOKEN', res.data)
						resolve()
						return;
					}
					reject('登录失败')
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 验证码登录
		SmsLogin({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				smsLogin(this.$axios, data).then(res => {
					if (res.code == 200) {
						setToken(res.data)
						commit('SET_TOKEN', res.data)
						resolve()
						return;
					}
					reject('登录失败')

				}).catch(error => {
					reject(error)
				})
			})
		},
		// 邮箱验证码登录
		EmailLogin({
			commit
		}, data) {
			return new Promise((resolve, reject) => {
				emailLogin(this.$axios, data).then(res => {
					if (res.code == 200) {
						setToken(res.data)
						commit('SET_TOKEN', res.data)
						resolve()
						return;
					}
					reject('登录失败')

				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getInfo(this.$axios).then(res => {
					const user = res.data
					setUserInfo(user)
					commit('SET_USER', user)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				logout(this.$axios, state.token).then(() => {
					removeToken()
					removeUserInfo()
					commit('SET_TOKEN', '')
					commit('SET_USER', null)
					resolve()
				}).catch(error => {
					removeToken()
					removeUserInfo()
					commit('SET_TOKEN', '')
					commit('SET_USER', null)
					resolve()
				})
			})
		},

		// 前端 登出
		FedLogOut({
			commit
		}) {
			return new Promise(resolve => {
				// 未登录 清除已登录状态
				removeToken()
				removeUserInfo()
				commit('SET_TOKEN', '')
				commit('SET_USER', null)
			})
		}
	}
}

export default user
